import java.util.HashMap;
import java.util.Map;

/**
 * @Classname TwoSum 两数之和为某个值
 * @Date 2021/12/23 8:51
 * @Created
 */
public class N001_TwoSum {

    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6};
        int[] ints = twoSum2(arr, 7);
        System.out.println(ints.toString());
    }
    //暴力
    public static int[] twoSum(int[] nums, int target) {
        for(int i =0;i<nums.length;i++){
            for(int j =i+1;j<nums.length;j++){
                if(nums[j] == target-nums[i]){
                    return new int[]{i,j};
                }
            }
        }
        return new int[]{};
    }

    public  static  int[] twoSum2(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i ++){
            int remainder = target - nums[i];
            if(map.containsKey(nums[i])) {
                return new int[]{map.get(nums[i]), i};
            }
            map.put(remainder, i);
        }
        throw new IllegalArgumentException("no solution.");
    }
}
